/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package org.apache.ranger.obs.server;

import org.apache.hadoop.conf.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * description
 *
 * @since 2021-10-13
 */
public class MiniServerUtil {
    protected static final Logger LOG = LoggerFactory.getLogger(MiniServerUtil.class);

    protected static List<MiniServer> miniservers = new ArrayList<>();

    public static void startDistributedMiniServer(List<Configuration> configurations, String principal)
        throws Exception {
        File workDir = new File(System.getProperty("test.dir", "/tmp"));
        MiniServer.startKdc(workDir, principal);

        for (Configuration conf : configurations) {
            MiniServer miniServer = new MiniServer(conf);
            Thread server1Thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        miniServer.start();
                    } catch (Exception e) {
                        new RuntimeException(e);
                    }
                }
            });
            server1Thread.setDaemon(true);
            server1Thread.start();
            while (!miniServer.isRunning()) {
                Thread.sleep(50);
            }
            miniservers.add(miniServer);
        }
    }

    public static void stopDistributedMiniServer() {
        MiniServer.stopKdc();
        for (MiniServer miniserver : miniservers) {
            miniserver.stop();
        }
    }
}
